package com.lottery.service.pc28.lobbyService.impl;

import com.alibaba.fastjson.JSON;
import com.lottery.dao.pc28.lobbyDao.WinningResultsDao;
import com.lottery.dao.pc28.statisticsDao.UserTop10Dao;
import com.lottery.dto.ResultDto;
import com.lottery.entity.LotteryExchange;
import com.lottery.entity.UserTop10;
import com.lottery.service.pc28.JedisClient;
import com.lottery.service.pc28.robotService.RobotUserService;
import com.lottery.service.pc28.lobbyService.WinningResultsService;
import com.lottery.utils.RobotParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Service
public class WinningResultsServiceImpl implements WinningResultsService {

	@Autowired
	private WinningResultsDao winningResultsDao;

	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private UserTop10Dao userTop10Dao;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	// 中奖信息标志key
	@Value("${PC28FLG}")
	private String FLG;
	// 当前开奖的期号
	@Value("${PC28EXPECT}")
	private String EXPECT;
	// 当前开奖的号码
	@Value("${PC28OPENCODE}")
	private String OPENCODE;
	// 当前开奖的时间
	@Value("${PC28OPENDATE}")
	private String OPENDATE;
	// 下一次开奖的时间
	@Value("${PC28NEXTTIME}")
	private String NEXTTIME;
	// 下一次开奖的期号
	@Value("${PC28NEXTEXPECT}")
	private String NEXTEXPECT;

	// 当前开奖的期号
	@Value("${SSCEXPECT}")
	private String sscget;
	// 当前开奖的号码
	@Value("${SSCOPENCODE}")
	private String sscopen;
	// 当前开奖的时间
	@Value("${SSCOPENDATE}")
	private String sscDate;
	// 下一次开奖的时间
	@Value("${SSCNEXTTIME}")
	private String sscTime;
	// 下一次开奖的期号
	@Value("${SSCNEXTEXPECT}")
	private String sscEXPECT;

	/**
	 * 开奖首页记录
	 * 
	 * @throws ParseException
	 */
	@Override
	public String showPage(int lotteyType) {
		ResultDto<Map<String, Object>> result = new ResultDto<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (lotteyType == 1) {
			// 获取期号
			String expect = jedisClient.get(sscget);
			// 获取开奖数字
			String opencode1 = jedisClient.get(sscopen);
			String opencode = opencode1.replace(",", "");
			// 获取下一期的开奖时间
			String nextTime = jedisClient.get(sscTime);
			// 获取距离开奖时间的时间差
			String dateTime = "";
			long minusSeconds = 0;
			try {

				long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nextTime).getTime();
				long currentTimeMillis = System.currentTimeMillis();

				minusSeconds = time - currentTimeMillis;
				SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");// 初始化Formatter的转换格式。
				dateTime = formatter.format(minusSeconds);

			} catch (ParseException e) {
				e.printStackTrace();
			}
			String[] str = opencode1.split(",");
			String rule = "";

			int amount = Integer.parseInt(str[0]) + Integer.parseInt(str[1]) + Integer.parseInt(str[2])
					+ Integer.parseInt(str[3]) + Integer.parseInt(str[4]);
			if (amount >= 23 && amount % 2 != 0) {
				rule = "大单";
			} else if (amount < 23 && amount % 2 != 0) {
				rule = "小单";
			} else if (amount >= 23 && amount % 2 == 0) {
				rule = "大双";
			} else if (amount < 23 && amount % 2 == 0) {
				rule = "小双";
			}

			// userTop10中奖金额统计
			int count = 0;
			Map<String, Object> params = new HashMap<>();
			map.put("expect", expect);
			map.put("lotteyType", lotteyType);
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();
			List<UserTop10> userTop10List = userTop10Dao.selectUserTop10List(map);
			// for (UserTop10 user : userTop10List) {
			// count = count + 1;
			// Map<String, String> userMap = new HashMap<String, String>();
			// String username = user.getUsername();
			// double userBetTotalMoney = user.getUserWinTotalMoney();
			// logger.info("************lotteyType****************{}", lotteyType);
			// if (lotteyType == 1) {
			//
			// String userTop = String.format("NO.%1$2s 恭喜%2$5s获得奖金 ￥%3$5s", count,
			// username,
			// String.format("%.2f", userBetTotalMoney - 0.005), lotteyType);
			// userMap.put("userTop", userTop);
			// } else if (lotteyType == 2) {
			// String userTop = String.format("NO.%1$2s 恭喜%2$5s获得奖金 ￥%3$5s", count,
			// username,
			// String.format("%.2f", userBetTotalMoney - 0.005), lotteyType);
			// userMap.put("userTop", userTop);
			// }
			//
			// list.add(userMap);
			// }

			List<UserTop10> robotSscWinList = new ArrayList<>();
			UserTop10 robotTop10 = null;
			logger.debug("robotOnlineUser::" + RobotUserService.arrayRobotOnline.size());
			for (Entry<Integer, ArrayList<LotteryExchange>> entry : RobotParams.robotSscWin.entrySet()) {
				try {
					int winTotalMoney = 0;
					int userId = 0;
					for (LotteryExchange one : entry.getValue()) {
						if (one.getWinningamount() > 0) {
							winTotalMoney += one.getWinningamount();
							userId = one.getUserId();
						}
					}

					if (winTotalMoney > 0) {
						if (RobotParams.robotinfoMap.containsKey(userId)) {
							String username = RobotParams.robotinfoMap.get(userId).getRobotName();
							robotTop10 = new UserTop10();
							robotTop10.setUserId(entry.getKey());
							robotTop10.setExpect(expect);
							robotTop10.setUserWinTotalMoney(winTotalMoney);
							robotTop10.setUsername(username);
							robotSscWinList.add(robotTop10);
						}
					}
				} catch (Exception e) {
					logger.error("robotTop10: ", e);
					continue;
				}
			}
			// 将数据库userTop10中的数据加入到robotSscWinList进行中奖金额排序,选出前10位
			for (UserTop10 user : userTop10List) {
				robotSscWinList.add(user);
			}
			// 快速排序
			int bc = robotSscWinList.size();
			if (bc != 0) {
				UserTop10 b = null;
				for (int i = 0; i < bc - 1; i++) {
					for (int j = i + 1; j <= bc - 1; j++) {
						try {
							if (robotSscWinList.get(i).getUserWinTotalMoney() < robotSscWinList.get(j)
									.getUserWinTotalMoney()) {
								b = robotSscWinList.get(i);
								robotSscWinList.set(i, robotSscWinList.get(j));
								robotSscWinList.set(j, b);
							}
						} catch (Exception e) {
							logger.error("paixu: ", e);
							continue;
						}
					}
				}
				// 合并后的top10信息显示
				for (int i = 0; i < 10; i++) {
					try {
						if (i > robotSscWinList.size() - 1) {
							break;
						}
						count += 1;
						UserTop10 user = robotSscWinList.get(i);
						Map<String, String> userMap = new HashMap<String, String>();
						String username = user.getUsername();
						double userBetTotalMoney = user.getUserWinTotalMoney();
						String userTop = String.format("NO.%1$2s 恭喜%2$5s获得奖金            ￥%3$5s", count, username,
								String.format("%.2f", userBetTotalMoney - 0.005));
						userMap.put("userTop", userTop);
						list.add(userMap);
					} catch (Exception e) {
						logger.error("Top10: ", e);
						continue;
					}

				}
			}

			if (minusSeconds < 0) {
				map.put("dateTime", "00:00");
			} else {
				map.put("dateTime", dateTime);
			}
			map.put("playInfo", rule);
			logger.debug("************rule****************:{}", rule);
			map.put("nextTime", nextTime);
			map.put("expect", expect);
			map.put("opencode", opencode);
			map.put("userTop10List", list);

			map.put("result", "0");
			map.put("msg", "成功");

		} else if (lotteyType == 2) {
			// 获取期号
			String expect = jedisClient.get(EXPECT);
			// 获取开奖数字
			String opencode1 = jedisClient.get(OPENCODE);
			String opencode = opencode1.replace(",", "");
			// 获取下一期的开奖时间
			String nextTime = jedisClient.get(NEXTTIME);
			// 获取距离开奖时间的时间差
			String dateTime = "";
			long minusSeconds = 0;
			try {

				long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nextTime).getTime();
				long currentTimeMillis = System.currentTimeMillis();
				minusSeconds = time - currentTimeMillis;
				SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");// 初始化Formatter的转换格式。
				dateTime = formatter.format(minusSeconds);

			} catch (ParseException e) {
				e.printStackTrace();
			}
			String[] str = opencode1.split(",");
			String rule = "";

			int amount = Integer.parseInt(str[0]) + Integer.parseInt(str[1]) + Integer.parseInt(str[2]);
			if (amount >= 13 && amount % 2 != 0) {
				rule = "大单";
			} else if (amount < 13 && amount % 2 != 0) {
				rule = "小单";
			} else if (amount >= 14 && amount % 2 == 0) {
				rule = "大双";
			} else if (amount < 14 && amount % 2 == 0) {
				rule = "小双";
			}
			// userTop10中奖金额统计
			int count = 0;
			Map<String, Object> params = new HashMap<>();
			map.put("expect", expect);
			map.put("lotteyType", lotteyType);
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();
			List<UserTop10> userTop10List = userTop10Dao.selectUserTop10List(map);
			// for (UserTop10 user : userTop10List) {
			// count = count + 1;
			// Map<String, String> userMap = new HashMap<String, String>();
			// String username = user.getUsername();
			// double userBetTotalMoney = user.getUserWinTotalMoney();
			// logger.info("************lotteyType****************{}", lotteyType);
			// if (lotteyType == 1) {
			//
			// String userTop = String.format("NO.%1$2s 恭喜%2$5s获得奖金 ￥%3$5s", count,
			// username,
			// String.format("%.2f", userBetTotalMoney - 0.005), lotteyType);
			// userMap.put("userTop", userTop);
			// } else if (lotteyType == 2) {
			// String userTop = String.format("NO.%1$2s 恭喜%2$5s获得奖金 ￥%3$5s", count,
			// username,
			// String.format("%.2f", userBetTotalMoney - 0.005), lotteyType);
			// userMap.put("userTop", userTop);
			// }
			// list.add(userMap);
			// }

			List<UserTop10> roboPc28WinList = new ArrayList<>();
			UserTop10 robotTop10 = null;
			logger.debug("robotOnlineUser::" + RobotUserService.arrayRobotOnline.size());
			for (Entry<Integer, ArrayList<LotteryExchange>> entry : RobotParams.robotPc28Win.entrySet()) {
				try {
					int winTotalMoney = 0;
					int userId = 0;
					for (LotteryExchange one : entry.getValue()) {
						if (one.getWinningamount() > 0) {
							winTotalMoney += one.getWinningamount();
							userId = one.getUserId();
						}
					}

					if (winTotalMoney > 0) {
						if (RobotParams.robotinfoMap.containsKey(userId)) {
							String username = RobotParams.robotinfoMap.get(userId).getRobotName();
							robotTop10 = new UserTop10();
							robotTop10.setUserId(entry.getKey());
							robotTop10.setExpect(expect);
							robotTop10.setUserWinTotalMoney(winTotalMoney);
							robotTop10.setUsername(username);
							roboPc28WinList.add(robotTop10);
						}
					}
				} catch (Exception e) {
					logger.error("robotTop10: ", e);
					continue;
				}
			}
			// 将数据库userTop10中的数据加入到robotSscWinList进行中奖金额排序,选出前10位
			for (UserTop10 user : userTop10List) {
				roboPc28WinList.add(user);
			}
			// 快速排序
			int bc = roboPc28WinList.size();
			if (bc != 0) {
				UserTop10 b = null;
				for (int i = 0; i < bc - 1; i++) {
					for (int j = i + 1; j <= bc - 1; j++) {
						try {
							if (roboPc28WinList.get(i).getUserWinTotalMoney() < roboPc28WinList.get(j)
									.getUserWinTotalMoney()) {
								b = roboPc28WinList.get(i);
								roboPc28WinList.set(i, roboPc28WinList.get(j));
								roboPc28WinList.set(j, b);
							}
						} catch (Exception e) {
							logger.error("paixu: ", e);
							continue;
						}
					}
				}
				// 合并后的top10信息显示
				for (int i = 0; i < 10; i++) {
					try {
						if (i > roboPc28WinList.size() - 1) {
							break;
						}
						count += 1;
						UserTop10 user = roboPc28WinList.get(i);
						Map<String, String> userMap = new HashMap<String, String>();
						String username = user.getUsername();
						double userBetTotalMoney = user.getUserWinTotalMoney();
						String userTop = String.format("NO.%1$2s 恭喜%2$5s获得奖金            ￥%3$5s", count, username,
								String.format("%.2f", userBetTotalMoney - 0.005));
						userMap.put("userTop", userTop);
						list.add(userMap);
					} catch (Exception e) {
						logger.error("Top10: ", e);
						continue;
					}

				}
			}

			if (minusSeconds < 0) {
				map.put("dateTime", "00:00");
			} else {
				map.put("dateTime", dateTime);
			}
			map.put("playInfo", rule);
			logger.debug("************rule****************:{}", rule);
			map.put("nextTime", nextTime);
			map.put("expect", expect);
			map.put("opencode", opencode);
			map.put("userTop10List", list);

			map.put("result", "0");
			map.put("msg", "成功");

		}

		return JSON.toJSONString(map);
	}

}
